<!DOCTYPE html>
<html>

<head>
    <title>线别分档展示</title>
    <script src="{{ url_for('static', filename='js/html2canvas.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/saveImage.js') }}"></script>
    <style>
        table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
        }

        th,
        td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #dddddd;
            transition: all 0.3s ease;
        }

        th {
            background-color: #009879;
            color: #ffffff;
            font-weight: bold;
        }

        tr:hover {
            background-color: #ffeb3b;
            transform: scale(1.05);
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
            font-weight: bold;
            transition: all 0.3s ease;
        }

        tr:nth-child(even) {
            background-color: #f3f3f3;
        }

        .disabled {
            position: relative;
            color: #999;
            pointer-events: none;
        }

        .disabled::after {
            content: '';
            position: absolute;
            left: 0;
            right: 0;
            top: 50%;
            height: 2px;
            background-color: #999;
            transform: rotate(0deg);
        }

        h1 {
            color: #009879;
            margin-bottom: 30px;
            text-align: center;
        }
        #query-form button {
            padding: 8px 16px;
            background-color: #009879;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        #query-form button:hover {
            background-color: #007f63;
        }
        #query-form label {
            font-weight: bold;
        }
    </style>
</head>

<body>
    
    <form id="query-form">
        <label for="workshop">车间：</label>
        <select id="workshop" name="workshop" required>
            <option value="S7">S7</option>
        </select>
        <label for="size">尺寸：</label>
        <select id="size" name="size" required>
            <option value="整片">整片</option>
            <option value="半片">半片</option>
            <option value="全部">全部</option>
        </select>
        <button type="submit">查询</button>
        <button id="save-button">保存为图片</button>
    </form>
    <div class="pngdown">
    <div id="app">
        <h1>线别分档展示</h1>
       
        <table>
            <thead>
                <tr>
                    <th>序号</th>
                    <th>车间</th>
                    <th>尺寸</th>
                    <th>线别</th>
                    <th>分档</th>
                </tr>
            </thead>
            <tbody id="data-body">
                <!-- 数据将动态插入 -->
            </tbody>
        </table>
    </div>
</div>
    <script>
         // 添加保存图片功能
         document.getElementById('save-button').addEventListener('click', () => {
            saveClassAsImage('pngdown')
        });
        // 添加排序功能
        const sortTable = (columnIndex, order) => {
            const table = document.querySelector('table');
            const tbody = table.querySelector('tbody');
            const rows = Array.from(tbody.querySelectorAll('tr'));

            rows.sort((a, b) => {
                const aValue = a.querySelectorAll('td')[columnIndex].textContent;
                const bValue = b.querySelectorAll('td')[columnIndex].textContent;

                // 尝试将值转换为数字
                const numA = parseFloat(aValue);
                const numB = parseFloat(bValue);

                // 如果两个值都是有效数字，则按数字排序
                if (!isNaN(numA) && !isNaN(numB)) {
                    return order === 'asc' ? numA - numB : numB - numA;
                }
                // 否则按字符串排序
                else {
                    return order === 'asc' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
                }
            });

            tbody.innerHTML = '';
            rows.forEach(row => tbody.appendChild(row));
        };


        // 为表头添加点击事件
        const headers = document.querySelectorAll('th');
        headers.forEach((header, index) => {
            header.addEventListener('click', () => {
                const currentOrder = header.dataset.order || 'asc';
                sortTable(index, currentOrder);
                header.dataset.order = currentOrder === 'asc' ? 'desc' : 'asc';
            });
        });
        async function fetchData() {
            try {
                const workshop = document.getElementById('workshop').value;
                const size = document.getElementById('size').value;
                const response = await fetch(`/api/ipconfig?workshop=${workshop}&size=${size}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();
                console.log('获取到的数据:', data);
                renderTable(data);
            } catch (error) {
                console.error('获取数据失败:', error);
                alert('数据加载失败，请检查网络连接并确保后端服务正在运行');
            }
        }

        function renderTable(data) {
            const tbody = document.getElementById('data-body');
            const colorMap = {};
            const colors = ['#FFCCCC', '#CCE5FF', '#FFFFCC', '#FF00FF', '#00BFFF', '#87CEFA', '#98FB98', '#F08FED', '#DDA0DD', '#FFA07A', '#F08080', '#FA8072', '#E9967A', '#FF6347', '#FF7F50', '#CD5C5C', '#DC143C', '#FF0000', '#B22222'];
            tbody.innerHTML = data.map((item, index) => {
                const grade = item.active_line_grade || 'empty';
                if (!colorMap[grade]) {
                    colorMap[grade] = colors[Object.keys(colorMap).length % colors.length];
                }
                return `
                    <tr class="${item.enabled ? '' : 'disabled'}" style="background-color: ${colorMap[grade]};">
                        <td>${index + 1}</td>
                        <td>${item.workshop}</td>
                        <td>${item.size}</td>
                        <td>${item.line}</td>
                        <td>${item.active_line_grade || ''}</td>
                    </tr>
                `;
            }).join('');
        }

        // 添加表单提交事件处理
        document.getElementById('query-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const workshop = document.getElementById('workshop').value;
            const size = document.getElementById('size').value;
            
            try {
                const response = await fetch(`/api/ipconfig?workshop=${workshop}&size=${size}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();
                console.log('获取到的数据:', data);
                renderTable(data);
            } catch (error) {
                console.error('获取数据失败:', error);
                alert('数据加载失败，请检查网络连接并确保后端服务正在运行');
            }
        });

        document.addEventListener('DOMContentLoaded', fetchData);
        setInterval(fetchData, 600000); // 每分钟自动刷新数据
    </script>
</body>

</html>